package com.glela.order.service.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glela.common.util.DateUtil;
import com.glela.common.util.NumberUtil;
import com.glela.mq.service.OrderQueueService;
import com.glela.order.mapper.CommisionMapper;
import com.glela.order.mapper.OrderInfoMapper;
import com.glela.order.mapper.OrderObjectMapper;
import com.glela.order.model.Commision;
import com.glela.order.model.OrderInfo;
import com.glela.order.model.OrderObject;
import com.glela.platform.mapper.UndefinedUserMapper;
import com.glela.platform.model.UndefinedUser;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.UserService;
import com.zls.commons.msg.SourceSys;
import com.zls.wx.message.CommissionArrivalMsg;
import com.zls.wx.message.MarketingSuccessMsg;

@Service
public class NotifyWxMsgServiceImpl {
	private Logger				logger	= LoggerFactory.getLogger(NotifyWxMsgServiceImpl.class);
	@Autowired
	private OrderQueueService	orderQueueService;

	@Autowired
	private CommisionMapper		commisionMapper;
	@Autowired
	private UserService			userService;
	@Autowired
	private OrderObjectMapper	orderObjectMapper;
	@Autowired
	private OrderInfoMapper		orderInfoMapper;
	@Autowired
	private UndefinedUserMapper	undefinedUserMapper;

	/**
	 * <dl>
	 * <dt>发送微信模版消息-推荐销售成功</dt>
	 * </dl>
	 * @param objId 父订单ID
	 * @author zls
	 * @date 2018年1月30日 下午1:25:49
	 */
	public void sendWxTemplateMsgMarketingSuccess(Long objId) {
		try {
			if (objId == null || objId <= 0) {
				logger.warn("推荐下单完成，未发送微信模版消息提醒预计分润金额。父订单id为空：{}", objId);
				return;
			}
			//校验订单信息
			OrderObject checkObjOrder = orderObjectMapper.selectByPrimaryKey(objId);
			if (checkObjOrder == null || checkObjOrder.getUserId() == null || checkObjOrder.getUserId() <= 0) {
				logger.warn("推荐下单完成，未发送微信模版消息提醒预计分润金额。父订单[{}]不存在", objId);
				return;
			}
			if (checkObjOrder.getUserId() == null || checkObjOrder.getUserId() <= 0) {
				logger.warn("推荐下单完成，未发送微信模版消息提醒预计分润金额。父订单[{}]的购买人[{}]不存在", objId, checkObjOrder.getUserId());
				return;
			}
			//校验购买人
			ResponseUser buyUser = userService.selectUserRoleFormCacheById(checkObjOrder.getUserId());
			if (buyUser == null) {
				logger.warn("推荐下单完成，未发送微信模版消息提醒预计分润金额。父订单[{}]的购买人[{}]不存在", objId, checkObjOrder.getUserId());
				return;
			}

			//获取分佣明细
			List<Commision> checkCommision = commisionMapper.selectByOrderObjectIdForCommision(objId);
			if (CollectionUtils.isNotEmpty(checkCommision)) {
				//用户每单获得直接分润总金额
				Map<Long, Map<Long, Long>> userCommisionMap = new HashMap<>();
				for (Commision commision : checkCommision) {
					if (commision != null) {
						//非直接分润跳过
						if (commision.getBusinessTypeId() == null || commision.getBusinessTypeId() != 2) {
							continue;
						}

						//累加每单分润金额
						Map<Long, Long> map = userCommisionMap.get(commision.getUserId());
						if (MapUtils.isEmpty(map) || map.get(commision.getOrderInfoId()) == null) {
							map = new HashMap<Long, Long>();
							userCommisionMap.put(commision.getUserId(), map);
						}
						map.put(commision.getOrderInfoId(), MapUtils.getLongValue(userCommisionMap, commision.getUserId(), 0l) + commision.getFee());
					}
				}
				Map<Long, OrderInfo> orderInfoMap = new HashMap<>();
				//每个分润用户发送消息
				for (Long userId : userCommisionMap.keySet()) {
					Map<Long, Long> map = userCommisionMap.get(userId);
					ResponseUser checkUser = userService.selectUserRoleFormCacheById(userId);
					if (checkUser != null && checkUser.isStoreLevel() && MapUtils.isNotEmpty(map)) {//分润用户及分润金额有效性
						//获取微信openId
						Set<String> openIdSet = getOpenIds(userId);
						if (CollectionUtils.isNotEmpty(openIdSet)) {
							/*封装模版消息*/
							for (Long orderInfoId : map.keySet()) {
								OrderInfo checkOrderInfo = orderInfoMap.get(orderInfoId);
								if (checkOrderInfo == null) {
									checkOrderInfo = orderInfoMapper.selectByPrimaryKey(orderInfoId);
									orderInfoMap.put(orderInfoId, checkOrderInfo);
								}
								if (checkOrderInfo == null) {
									continue;
								}

								MarketingSuccessMsg marketingSuccessMsg = new MarketingSuccessMsg(SourceSys.XIAOPU);
								//						marketingSuccessMsg.setTitle("你好，你已成功卖出。");
								//						marketingSuccessMsg.setRemark("感谢你的使用");
								marketingSuccessMsg.setOpenIds(openIdSet);
								marketingSuccessMsg.setOrderSn(checkOrderInfo.getOrderSn());
								marketingSuccessMsg.setOrderPayTime(StringUtils.substring(checkOrderInfo.getPayTime(), 0, 19));
								marketingSuccessMsg.setStoreUser(StringUtils.replaceAll(buyUser.getUserName(), "(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
								marketingSuccessMsg.setStoreName(checkUser.getNickName() + "的小铺");
								marketingSuccessMsg.setIncome(NumberUtil.getFloatPrice(MapUtils.getLongValue(map, orderInfoId, 0l)) + "元");

								orderQueueService.sendWxTemplateMsgMarketingSuccess(marketingSuccessMsg);
							}
						} else {
							logger.warn("推荐下单完成，未发送微信模版消息提醒预计分润金额。用户[{}]微信openIds为空", userId);
						}
					}
				}
			} else {
				logger.warn("订单【{}】无分润明细", objId);
			}
		} catch (Exception e) {
			logger.error("发送微信通知失败：{}", e.getMessage(), e);
		}
	}

	/** 获取openIds */
	Set<String> getOpenIds(long userId) {
		Set<String> undefinedUserIdSet = new HashSet<>();
		List<UndefinedUser> checkUndefinedUsers = undefinedUserMapper.selectByUserId(userId);
		for (UndefinedUser undefinedUser : checkUndefinedUsers) {
			if (undefinedUser != null && StringUtils.isNoneBlank(undefinedUser.getUndefinedId()) && undefinedUser.getUndefinedType() == 2) {
				undefinedUserIdSet.add(undefinedUser.getUndefinedId());
			}
		}
		return undefinedUserIdSet;
	}

	/**
	 * <dl>
	 * <dt>发送微信模版消息-佣金到账</dt>
	 * </dl>
	 * @param userName 用户帐号
	 * @param commisionFee 佣金金额
	 * @author zls
	 * @date 2018年2月5日 上午11:19:22
	 */
	public void sendWxTemplateMsgCommissionArrival(String userName, String commisionFee) {
		try {
			if (StringUtils.isBlank(userName) || !NumberUtils.isCreatable(commisionFee)) {
				logger.error("用户帐号或金额为空：{}-{}", userName, commisionFee);
				return;
			}
			ResponseUser user = userService.getUserByName(userName);
			if (user != null) {
				Set<String> openIds = getOpenIds(user.getUserId());
				if (CollectionUtils.isNotEmpty(openIds)) {
					CommissionArrivalMsg commissionArrivalMsg = new CommissionArrivalMsg(SourceSys.XIAOPU);
					commissionArrivalMsg.setTitle("哇！您又获得了一笔佣金奖励！");
					commissionArrivalMsg.setOpenIds(openIds);
					commissionArrivalMsg.setIncome(NumberUtil.formatTowDecimal(NumberUtils.toFloat(commisionFee, 0)) + "元");
					commissionArrivalMsg.setInTime(DateUtil.getNow());
					orderQueueService.sendWxTemplateMsgCommissionArrival(commissionArrivalMsg);
				}
			}
		} catch (Exception e) {
			logger.error("发送微信模版消息-佣金到账失败：{}", e.getMessage(), e);
		}
	}
}
